package ticketing_system.Database;


import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DBHelper {
    private DataSource ds;

    public DBHelper(DataSource ds) {
        this.ds = ds;
    }

    public int doUpData(String sql, Object... paras) throws Exception {
        Connection conn = this.ds.getConnection();
        PreparedStatement stat = conn.prepareStatement(sql);
        for (int i = 0; i < paras.length; i++) {
            stat.setObject(i + 1, paras[i]);
        }
        int result = stat.executeUpdate();
        conn.close();
        return result;
    }

    public Object doQuery(String sql, Handler handler, Object... paras) throws Exception {
        Connection conn = this.ds.getConnection();
        PreparedStatement stat = conn.prepareStatement(sql);
        for (int i = 0; i < paras.length; i++) {
            stat.setObject(i + 1, paras[i]);
        }
        ResultSet rs = stat.executeQuery();
        Object r = handler.handle(rs);

        conn.close();
        return r;
    }

//    public Object doExist(String sql, Handler handler,Object... paras) throws Exception {
//        Connection conn = this.ds.getConnection();
//        PreparedStatement stat = conn.prepareStatement(sql);
//        for (int i = 0; i < paras.length; i++) {
//            stat.setObject(i + 1, paras[i]);
//        }
//        ResultSet rs = stat.executeQuery();
//        Object r = handler.handle(rs);
//        if (r!=null){
//            System.out.println("您已成功登陆");
//        }else {
//
//        }
//        conn.close();
//        return r;
//    }
}
